<?php

namespace App\ModelFilters;

use Carbon\Carbon;
use EloquentFilter\ModelFilter;

class DocumentOrderFilter extends ModelFilter
{
    /**
    * Related Models that have ModelFilters as well as the method on the ModelFilter
    * As [relationMethod => [input_key1, input_key2]].
    *
    * @var array
    */
    public $relations = [];

    public function status($v)
    {
        if ($v == 22) {
            return $this->where('status', 2)->whereNull('address');
        }
        if ($v == 2 && request()->is('api/*')) {
            return $this->where('status', 2)->whereNotNull('address');
        }
        if (!is_null($v) && $v != "null") {
            if (!is_array($v)) $v = array_filter(explode(',', $v));
            return $this->whereIn('status', $v);
        }
    }

    public function nickname($v) {
        return $this->whereHas('user', function ($q) use ($v) {
            $q->where('nickname', 'like', '%'.$v.'%');
        });
    }

    public function mobile($v) {
        return $this->whereHas('user', function ($q) use ($v) {
            $q->where('mobile', $v);
        });
    }

    public function no($v) {
        return $this->where('tradeNo', $v)->orWhere('wxTradeNo', $v);
    }

    public function id($value) {
        return $this->where('id', $value);
    }

    public function userId($value) {
        return $this->where('userId', $value);
    }

    public function buyAt($v) {
        return $this->whereBetween('buyAt', [
            Carbon::parse($v)->startOfDay(),
            Carbon::parse($v)->endOfDay()
        ]);
    }

    public function payAt($v) {
        return $this->whereBetween('payAt', [
            Carbon::parse($v)->startOfDay(),
            Carbon::parse($v)->endOfDay()
        ]);
    }

    public function sendAt($v) {
        return $this->whereBetween('sendAt', [
            Carbon::parse($v)->startOfDay(),
            Carbon::parse($v)->endOfDay()
        ]);
    }

    public function print($v) {
        if ($v == 1) {
            return $this->whereNotNull('address');
        }
        if ($v == 2) {
            return $this->whereNull('address');
        }
    }
}
